package thoven.achievement.net.ideapluginachievement.listener

import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.WindowManagerEx
import thoven.achievement.net.ideapluginachievement.service.CodeStatsService
import java.awt.event.WindowEvent
import java.awt.event.WindowFocusListener as AwtWindowFocusListener

/**
 * 窗口焦点监听器
 * 用于检测"鸡你太美"成就（频繁切换窗口）
 */
class WindowFocusListener(private val project: Project) : AwtWindowFocusListener {
    
    private val LOG = logger<WindowFocusListener>()
    private var lastFocusTime = 0L
    
    override fun windowGainedFocus(e: WindowEvent?) {
        try {
            val currentTime = System.currentTimeMillis()
            
            // 如果距离上次获得焦点时间很短（比如5秒内），认为是频繁切换
            if (lastFocusTime > 0 && (currentTime - lastFocusTime) < 5000) {
                val codeStatsService = CodeStatsService.getInstance(project)
                codeStatsService.recordWindowSwitch()
                
                LOG.debug("检测到窗口快速切换")
            }
            
            lastFocusTime = currentTime
        } catch (e: Exception) {
            LOG.error("处理窗口获得焦点事件时出错", e)
        }
    }
    
    override fun windowLostFocus(e: WindowEvent?) {
        // 不需要特别处理失去焦点事件
    }
    
    /**
     * 注册窗口焦点监听器
     */
    fun register() {
        try {
            val windowManager = WindowManager.getInstance() as? WindowManagerEx
            val frame = windowManager?.getFrame(project)
            frame?.addWindowFocusListener(this)
            
            LOG.debug("窗口焦点监听器已注册")
        } catch (e: Exception) {
            LOG.error("注册窗口焦点监听器时出错", e)
        }
    }
    
    /**
     * 取消注册窗口焦点监听器
     */
    fun unregister() {
        try {
            val windowManager = WindowManager.getInstance() as? WindowManagerEx
            val frame = windowManager?.getFrame(project)
            frame?.removeWindowFocusListener(this)
            
            LOG.debug("窗口焦点监听器已取消注册")
        } catch (e: Exception) {
            LOG.error("取消注册窗口焦点监听器时出错", e)
        }
    }
}
